/*
 Copyright (C) 2010 QDSS.org
 
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.qdss.bizz.security.member;

import java.io.Serializable;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

import org.qdss.bizz.privileges.Privileges;
import org.qdss.bizz.security.AccessDeniedException;
import org.qdss.bizz.security.EntityPrivileges;

/**
 * 角色
 * 
 * @author <a href="mailto:zhaofang123@gmail.com">Zhao Fangfang</a>
 * @since 0.2, 2010-10-4
 * @version $Id: Role.java 7 2011-05-15 16:40:50Z zhaofang123@gmail.com $
 */
public class Role extends MemberGroup {
	private static final long serialVersionUID = -8635993188721946096L;

	private Map<Integer, Privileges> allPrivileges = new HashMap<Integer, Privileges>();
	
	/**
	 * @param identity
	 * @param name
	 * @param disabled
	 */
	public Role(Serializable identity, String name, boolean disabled) {
		super(identity, name, disabled);
	}
	
	@Override
	public boolean addMember(Principal user) {
		if (!super.addMember(user))
			return false;
		((User) user).setOwningRole(this);
		return true;
	}
	
	@Override
	public boolean removeMember(Principal user) {
		if (!super.removeMember(user))
			return false;
		((User) user).setOwningRole(null);
		return true;
	}
	
	/**
	 * 添加实体权限
	 * 
	 * @param priv
	 */
	public void addPrivileges(Privileges priv) {
		int e = ((EntityPrivileges) priv).getEntity();
		allPrivileges.put(e, priv);
	}
	
	/**
	 * 是否包含指定实体权限
	 * 
	 * @param entity
	 * @return
	 */
	public boolean hasPrivileges(int entity) {
		return allPrivileges.containsKey(entity);
	}
	
	/**
	 * 获取指定实体权限
	 * 
	 * @param entity
	 * @return
	 * @throws AccessDeniedException If {@link #hasPrivileges(int)} returns <tt>false</tt>
	 */
	public Privileges getPrivileges(int entity) throws AccessDeniedException {
		if (!hasPrivileges(entity))
			throw new AccessDeniedException("No such entity privileges: " + entity);
		return allPrivileges.get(entity);
	}
}
